package com.mininglamp.app.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.mininglamp.app.entity.User;
import com.mininglamp.app.response.Response;
import com.mininglamp.app.service.UserService;
import com.mininglamp.app.util.ResponseHelper;

@RestController
public class UserController {

	private static final Logger log = LoggerFactory.getLogger(UserController.class);

	@Resource
	private UserService service;

	@RequestMapping(value = "/hello", method = RequestMethod.GET)
	public Response hello(@RequestParam(required = false) String name, @RequestHeader("key") String key) {
		return ResponseHelper.OK("hello, " + name);
	}

	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public Response getUsers() {
		List<User> users = service.getUsers();
		return ResponseHelper.listObjResponse(users);
	}

	@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
	public Response getUser(@PathVariable(name = "id") int id) {
		User user = service.getUser(id);
		log.info("{}", user);
		return ResponseHelper.objResponse(user);
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(String username, HttpSession session) {
		log.info("username = {}", username);
		session.setAttribute("user", username);
		return "ok";
	}

	@RequestMapping(value = "userinfo", method = RequestMethod.GET)
	public Response userInfo(HttpSession session) {
		Object user = session.getAttribute("user");
		return ResponseHelper.OK(user == null ? "user is null" : user.toString());
	}
}
